<?php
namespace App\Repositories;

use App\Item;
use App\Repositories\BaseRepository;
use App\Scopes\StatusScope;

class ItemRepository {
	use BaseRepository;

	protected $model, $table_name;

	public function __construct(Item $item) {
		$this->model = $item;
		$this->table_name = 'items';
	}

	protected function searchColumn($query, $where) {
		return $query->when(array_key_exists('title', $where), function ($query) use ($where) {
			return $query->where('title', 'like', "%{$where['title']}%");
		})->when(array_key_exists('cate_name', $where), function ($query) use ($where) {
			return $query->whereHas('cate', function ($query) use ($where) {
				return $query->withoutGlobalScope(StatusScope::class)->where('cate_name', 'like', "%{$where['cate_name']}%");
			});
		});
	}

	public function indexPage($page = 1, $page_size = 6, $where, $sort = 'asc', $sortColumn = 'items.id') {
		$fields = ['id', 'cate_id', 'title', 'briefly', 'status', 'see_nums', 'allow_comment', 'approve_nums', 'comment_nums', 'created_at'];
		extract($where);
		return $this->model->select($fields)->has('cate')->when($title, function ($query) use ($title) {
			return $query->where('title', 'like', '%' . $title . '%');
		})->when($cate_id, function ($query) use ($cate_id) {
			return $query->where('cate_id', $cate_id);
		})->when($tag_id, function ($query) use ($tag_id) {
			return $query->whereHas('tags', function ($query) use ($tag_id) {
				return $query->where('tags.id', $tag_id);
			});
		})->offset(($page - 1) * $page_size)->limit($page_size)->orderBy($sortColumn, $sort)->take($page_size)->get();
	}

	public function countIndexRaws($where) {
		extract($where);
		return $this->model->has('cate')->when($title, function ($query) use ($title) {
			return $query->where('title', 'like', '%' . $title . '%');
		})->when($cate_id, function ($query) use ($cate_id) {
			return $query->where('cate_id', $cate_id);
		})->when($tag_id, function ($query) use ($tag_id) {
			return $query->whereHas('tags', function ($query) use ($tag_id) {
				return $query->where('tags.id', $tag_id);
			});
		})->count();
	}

	public function syncTags(array $tags = []) {
		if (!$tags) {
			return true;
		}
		$this->model->tags()->sync($tags);
	}

	public function getTopic($id) {
		return $this->model->has('cate')->findOrfail($id);
	}
}